package com.spring.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spring.boot.entity.Users;
import com.spring.boot.entity.server.CommonResult;
import com.spring.boot.entity.server.PlatformUser;
import com.spring.boot.entity.server.ServerEntity;
import com.spring.boot.service.UsersService;
import com.spring.boot.tool.Encode;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.Key;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 刘骄阳
 * 2021-07-16 18:34
 */
@Service
public class UsersServiceImpl implements UsersService {

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 后台管理登录
     *
     * @param users 用户对象
     * @return 数据
     */
    @Override
    public CommonResult rootLogin(Users users) {
        //  用户验证
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(users.getUsername(), users.getPassword()));
        PlatformUser user = (PlatformUser) authentication.getPrincipal();

        if (user == null) {
            return new CommonResult().failed("登录失败!");
        }
        //登录成功加入到上下文,重要
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new CommonResult().success(user.getToken());
    }
}
